﻿using System.IO;

using Ninject;
using Ninject.Modules;

using System.Net.DnsToolkit.Packet;
using System.Net.DnsToolkit.Serializer.Stream.Writer;
using System.Net.DnsToolkit.Serializer.Stream.Writer.Record;
using System.Net.DnsToolkit.Serializer.Stream.Compression;

namespace System.Net.DnsToolkit.Serializer.Stream.Extension {
    public static class MessageExtension {

        private static IMessageWriter<System.IO.Stream> _writer;
        static MessageExtension() {

            using (IKernel kernel = new StandardKernel(new DnsWriterStreamModule())) {
                _writer = kernel.Get<IMessageWriter<System.IO.Stream>>();
            }

        }
        
        public class DnsWriterStreamModule : NinjectModule {
            public override void Load() {

                Bind<IMessageWriter<System.IO.Stream>>().To<MessageWriter>();
                Bind<IHeaderWriter<System.IO.Stream>>().To<HeaderWriter>();
                Bind<IQuestionWriter<System.IO.Stream>>().To<QuestionWriter>();
                Bind<IRRWriter<System.IO.Stream>>().To<RRWriter>();
                Bind<IRecordWriterProvider<System.IO.Stream>>().To<RecordWriterProvider>();
                Bind<ICompressionInitializer>().To<StaticCompressionInitializer>();

                Bind<IRecordWriter<System.IO.Stream>>().To<RecordAAAAWriter>();
                Bind<IRecordWriter<System.IO.Stream>>().To<RecordAWriter>();
                Bind<IRecordWriter<System.IO.Stream>>().To<RecordCNAMEWriter>();
                Bind<IRecordWriter<System.IO.Stream>>().To<RecordMXWriter>();
                Bind<IRecordWriter<System.IO.Stream>>().To<RecordNSWriter>();
                Bind<IRecordWriter<System.IO.Stream>>().To<RecordPTRWriter>();
                Bind<IRecordWriter<System.IO.Stream>>().To<RecordSOAWriter>();


            }
        }

        public static byte[] GetBytes(this IMessage message) {
            return message.GetBytes(true);
        }

        public static byte[] GetBytes(this IMessage message, bool useCompression) {

            using (MemoryStream stream = new MemoryStream()) {
                _writer.Write(stream, message, useCompression);
                return stream.ToArray();
            }

        }

    }
}
